package tij4.concurrent.source;

import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.function.IntToDoubleFunction;

//从线程执行的任务中返回值,返回的值既是callable泛型给定的类型
class TaskWithResult implements Callable<String> {

    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    @Override
    public String call() throws Exception {
        return "result of TaskWithResult : "+id;
    }
}

public class CallableDemo{
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        ArrayList<Future<String>> futures = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(new TaskWithResult(i)));
        }

        for (Future<String> future : futures){
            try{
                System.out.println(future.get());
            }catch (InterruptedException e){
                System.out.println(e);
                return;
            }catch (ExecutionException e){
                System.out.println(e);
            }finally {
                executorService.shutdown();
            }

        }
    }
}
